package com.imooc.security.browser.config;

import com.imooc.security.core.properties.SecurityProperties;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter;
import org.springframework.security.core.annotation.AuthenticationPrincipal;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.security.web.authentication.AuthenticationFailureHandler;
import org.springframework.security.web.authentication.AuthenticationSuccessHandler;

/**
 * 自定义SpringSecurity核心基本配置
 *  WebSecurityConfigurerAdapter：关于WEb安全的适配器
 * @author JackYang
 * @description:
 * @create: 2020/6/14 19:14
 */
@Configuration
public class BrowserSecurityConfig extends WebSecurityConfigurerAdapter {
    
    @Autowired
    private SecurityProperties securityProperties;
    @Autowired
    private AuthenticationSuccessHandler imoocAuthenticationSuccessHandler;
    @Autowired
    private AuthenticationFailureHandler imoocAuthenticationFailureHandler;
    
    /**
     * 注入加密方式
     */
    @Bean
    public PasswordEncoder createPasswordEncoder(){
        return new BCryptPasswordEncoder();
    }
    
    /**
     * 重写该方法
     */
    @Override
    public void configure(HttpSecurity http) throws Exception {
             //以表单形式登录
        http.formLogin()
                //指定登陆页面
                .loginPage("/authentication/require")
                //"/authentication/form"是表单提交的请求路径。下面这代码表示，对于如下的的URL请求会交给UsernamePasswordAuthenticationFilter 去进行认证
                .loginProcessingUrl("/authentication/form")
                //指定登陆成功处理器
                .successHandler(imoocAuthenticationSuccessHandler)
                //指定登陆失败理器
                .failureHandler(imoocAuthenticationFailureHandler)
                .and()
                //任何请求都要验证
                .authorizeRequests()
                //不拦截的URL
                .mvcMatchers("/authentication/require",securityProperties.getBrowser().getLoginPage()).permitAll()
                //映射任何请求
                .anyRequest()
                //指定任何经过身份验证的用户都允许使用URL
                .authenticated()
                .and()
                //关闭跨域
                .csrf().disable();
                
    }
}
